package com.sams.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.sams.entity.Processmanage;
import com.sams.entity.SpotUpload;
import com.sams.entity.User;
import com.sams.service.BaseInfoService;
import com.sams.service.DataTotalService;
import com.sams.service.ProcessmanageService;
import com.sams.service.SchoolService;
import com.sams.util.SamResult;

@RequestMapping("/process")
@Controller
public class ProcessmanagerController {

	@Autowired
	private ProcessmanageService service;
	@Autowired
	private BaseInfoService baseInfoService;
	@Autowired
	private DataTotalService dataTotalService;
	@Autowired
	private SchoolService schoolService;
	@RequestMapping("/list")
	public String ListProcess(Integer currentPage,Model model,Integer schid,Integer status,
			Integer zid,String x,
			HttpServletRequest request,HttpSession session) {
		if(currentPage==null) {
			currentPage=1;
		}
		User user =  (User)request.getSession().getAttribute("user");
		if(user==null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		//分页查询时，条件的来源 
		if(x!=null) {// 说明是分页信息
			//从session中获取条件
			status=(Integer)session.getAttribute("status");
			schid=(Integer)session.getAttribute("schid");
			zid=(Integer)session.getAttribute("zid");
		}
		//查询所有的乡镇
		if(user.getRoleid()==1 ||user.getRoleid()==2) {
			 //查询所有镇id
			model.addAttribute("xzList", baseInfoService.findById(user.getZid()));
		}else { 
			 model.addAttribute("xzList", dataTotalService.selectAllZhen());
		}
		PageInfo<Processmanage> pageInfo=service.ListPro(currentPage,schid,status,user,zid);
		model.addAttribute("pageInfo", pageInfo);
		session.setAttribute("schid",schid);
		session.setAttribute("status",status);
		session.setAttribute("zid", zid);
		//如果已选zid ，则需要回显它对应的学校，方便继续选择其他学校
		if(zid!=null && !zid.toString().equals("0")) {
			model.addAttribute("schoolListByZid",schoolService.selectSchoolByZid(zid));
		}
		return "processmanage";		
	}
	
	@RequestMapping("/add")
	public String add(@RequestParam("titlefile") String titlefile
			,@RequestParam("basicfile")MultipartFile basicfile
			,@RequestParam("promisefile")MultipartFile promisefile
			,@RequestParam("leaderfile")MultipartFile leaderfile
			,@RequestParam("assessfile")MultipartFile assessfile
			,@RequestParam("mettingfile")MultipartFile mettingfile
			,@RequestParam("signaturefile")MultipartFile signaturefile
			,@RequestParam("bankfile")MultipartFile bankfile
			,@RequestParam("schid")String schid
			,Model model
			,HttpServletRequest request) {
		User user =  (User)request.getSession().getAttribute("user");
		if(user==null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		Properties properties = new Properties();
		   InputStream inputStream = ProcessmanagerController.class.getClassLoader().getResourceAsStream("db.properties");
		         try {
		   properties.load(inputStream);
		  } catch (IOException e) {
		   // TODO Auto-generated catch block
		   e.printStackTrace();
		  }
		  File file=new File(properties.getProperty("imagePath")+File.separator+"processmanager");       
         if(!file.exists()){//如果文件夹不存在
 			file.mkdirs();//创建文件夹
 		}
         
         String newbasicfile=getFileName(basicfile.getOriginalFilename());
         String newpromisefile=getFileName(promisefile.getOriginalFilename());
         String newleaderfile=getFileName(leaderfile.getOriginalFilename());
         String newassessfile=getFileName(assessfile.getOriginalFilename());
         String newmettingfile=getFileName(mettingfile.getOriginalFilename());
         String newsignaturefile=getFileName(signaturefile.getOriginalFilename());
         String newbankfile=getFileName(bankfile.getOriginalFilename());
         try {
			
			basicfile.transferTo(new File(file.getPath()+File.separator+newbasicfile));
			promisefile.transferTo(new File(file.getPath()+File.separator+newpromisefile));
			leaderfile.transferTo(new File(file.getPath()+File.separator+newleaderfile));
			assessfile.transferTo(new File(file.getPath()+File.separator+newassessfile));
			mettingfile.transferTo(new File(file.getPath()+File.separator+newmettingfile));
			signaturefile.transferTo(new File(file.getPath()+File.separator+newsignaturefile));
			bankfile.transferTo(new File(file.getPath()+File.separator+newbankfile));
			Processmanage pro=new Processmanage();
			pro.setTitle(titlefile);
			pro.setBasicfile("processmanager/"+newbasicfile);
			pro.setPromisefile("processmanager/"+newpromisefile);
			pro.setLeaderfile("processmanager/"+newleaderfile);
			pro.setAssessfile("processmanager/"+newassessfile);
			pro.setMeetingfile("processmanager/"+newmettingfile);
			pro.setSignaturefile("processmanager/"+newsignaturefile);
			pro.setBankfile("processmanager/"+newbankfile);
			pro.setUid(user.getId());
			pro.setSchid(Integer.valueOf(schid));
			pro.setStatus(1);			
			pro.setFinishdate(new Date());
			int count = service.add(pro);
			
			return "forward:/process/list";
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "error";
		}
                  		
	}
	//新文件名字
	public String getFileName(String fileName) {
		String filePrefix=fileName.substring(0,fileName.lastIndexOf('.'));
        String fileSuffix=fileName.substring(fileName.lastIndexOf('.'), fileName.length());
       return filePrefix+(int)(Math.random()*9000+1000)+fileSuffix;
	}
	//删除
	@RequestMapping("/delete")
	public String delete(@RequestParam("id")String id,Model model) {
		
		int count = service.delete(Integer.valueOf(id));
		if(count!=0) {
			return "forward:/process/list";
		}else {
			model.addAttribute("error", "状态不为初稿,不能删除");
			return "error";
		}
		
	}
	//上报
	@ResponseBody
	@RequestMapping("/report")
	public SamResult report(Integer id,Integer status,HttpSession session)
	{
		SamResult result = new SamResult();
		//获取用户的session
		User user =  (User)session.getAttribute("user");
		if(user==null) {
			//model.addAttribute("error", "会话过期，请重新登录");
			   result.setMsg("会话过期，请重新登录");
			   return result;
		}
		//验证该用户是否可以继续上报  
		// 对于学校账号，草稿状态的数据，可以继续操作
		// 对于镇账号  ，状态为1的数据 可以继续操作
		// 对于县账号，状态为2的数据  
		
		boolean flag=false;
		if(user.getRoleid()==1 && status==1) {
			flag=true;//可以继续
		}else if(user.getRoleid()==2 && status==2) {
			flag=true;
		}else if(user.getRoleid()==3 && status==3) {
			flag=true;
		}
	   if(flag) {
			int count =service.report(id);
			if(count>0) {
				 result.setData(count); //上报的数据条数
				 result.setStatus(200);
				 if(status==3) { //即将变为4  归档
					 result.setMsg("数据归档成功，已归档"+count+"条数据,可在数据查询菜单中查看");
				 }else {
					 result.setMsg("上报成功，已上报领导"+count+"条数据");
				 }
			}else {
				 
				 result.setData(count); //上报的数据条数
				 result.setStatus(-1);
				 result.setMsg("数据上报失败");
			}
			return result;
	   }else {
		   
			 result.setStatus(-1);
			 result.setMsg("对于当前状态的数据，您没有继续上报的权限。");
			 return result;
	   }
		
		
	}
	//撤销上报
	@ResponseBody
	@RequestMapping("/noreport")
	public SamResult noReport(Integer id,Integer status,HttpSession session)
	{
		SamResult result = new SamResult();
		//获取用户的session
		User user =  (User)session.getAttribute("user");
		if(user==null) {
			//model.addAttribute("error", "会话过期，请重新登录");
			   result.setMsg("会话过期，请重新登录");
			   return result;
		}
		boolean flag=false;
		if(user.getRoleid()==2 && status==2) {
			flag=true;//可以撤销
		}else if(user.getRoleid()==3 && status==3) {
			flag=true;
		} 
		
		if(flag) {
			int count =service.noreport(id);
			if(count>0) {
				 result.setData(count); //上报的数据条数
				 result.setStatus(200);
			 
				 result.setMsg("撤销成功，已撤销数据"+count+"条数据");
				 
			}else {
				 
				 result.setData(count); //上报的数据条数
				 result.setStatus(-1);
				 result.setMsg("数据上报失败");
			}
			return result;
		}else {
			 result.setStatus(-1);
			 result.setMsg("对于当前状态的数据，您没有撤销数据的权限。");
			 return result;
		}
	}
	//修改查询
	@RequestMapping("/updatePro")
	public String updatePro(Integer id,HttpServletRequest request,Model model) {
		User user = (User) request.getSession().getAttribute("user");
		if (user == null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		Processmanage processmanage = service.findById(id);
		model.addAttribute("pro", processmanage);
		
		return "updatePro";
		
	}
	//修改
	@RequestMapping("/update")
	public String update(@RequestParam("id") String id
			,@RequestParam("titlefile") String titlefile
			,@RequestParam("basicfile")MultipartFile basicfile
			,@RequestParam("promisefile")MultipartFile promisefile
			,@RequestParam("leaderfile")MultipartFile leaderfile
			,@RequestParam("assessfile")MultipartFile assessfile
			,@RequestParam("mettingfile")MultipartFile mettingfile
			,@RequestParam("signaturefile")MultipartFile signaturefile
			,@RequestParam("bankfile")MultipartFile bankfile
			,@RequestParam("schid")String schid
			,Model model
			,HttpServletRequest request) {
		User user =  (User)request.getSession().getAttribute("user");
		if(user==null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		Properties properties = new Properties();
		   InputStream inputStream = ProcessmanagerController.class.getClassLoader().getResourceAsStream("db.properties");
		         try {
		   properties.load(inputStream);
		  } catch (IOException e) {
		   // TODO Auto-generated catch block
		   e.printStackTrace();
		  }
		  File file=new File(properties.getProperty("imagePath")+File.separator+"processmanager");       
         if(!file.exists()){//如果文件夹不存在
 			file.mkdirs();//创建文件夹
 		}
         
         String newbasicfile=getFileName(basicfile.getOriginalFilename());
         String newpromisefile=getFileName(promisefile.getOriginalFilename());
         String newleaderfile=getFileName(leaderfile.getOriginalFilename());
         String newassessfile=getFileName(assessfile.getOriginalFilename());
         String newmettingfile=getFileName(mettingfile.getOriginalFilename());
         String newsignaturefile=getFileName(signaturefile.getOriginalFilename());
         String newbankfile=getFileName(bankfile.getOriginalFilename());
         try {
			
			basicfile.transferTo(new File(file.getPath()+File.separator+newbasicfile));
			promisefile.transferTo(new File(file.getPath()+File.separator+newpromisefile));
			leaderfile.transferTo(new File(file.getPath()+File.separator+newleaderfile));
			assessfile.transferTo(new File(file.getPath()+File.separator+newassessfile));
			mettingfile.transferTo(new File(file.getPath()+File.separator+newmettingfile));
			signaturefile.transferTo(new File(file.getPath()+File.separator+newsignaturefile));
			bankfile.transferTo(new File(file.getPath()+File.separator+newbankfile));
			Processmanage pro=service.findById(Integer.valueOf(id));
			
			pro.setTitle(titlefile);
			pro.setBasicfile("processmanager/"+newbasicfile);
			pro.setPromisefile("processmanager/"+newpromisefile);
			pro.setLeaderfile("processmanager/"+newleaderfile);
			pro.setAssessfile("processmanager/"+newassessfile);
			pro.setMeetingfile("processmanager/"+newmettingfile);
			pro.setSignaturefile("processmanager/"+newsignaturefile);
			pro.setBankfile("processmanager/"+newbankfile);
			pro.setUid(user.getId());
			pro.setSchid(Integer.valueOf(schid));						
			pro.setFinishdate(new Date());
			int count = service.add(pro);			
			return "forward:/process/list";
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			model.addAttribute("error", "修改失败");
			return "error";
		}
		
	}
}
